import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {animate, state, style, transition, trigger} from "@angular/animations";
import {AppService} from "../../../app.service";
import {GlobalEvent} from "../../../support/event.definition";

interface Message {
  type: string;
  display: boolean;
  message?: string;
  timeout: number;
}

const TypeMapping: Map<string, string> = new Map<string, string>([
  [GlobalEvent.ShowHeadtipsInfo, "info"],
  [GlobalEvent.ShowHeadtipsWarning, "warning"],
  [GlobalEvent.ShowHeadtipsError, "error"],
])

@Component({
  selector: 'ss-platform-headtips',
  template: `
    <div class="ss-platform-headtips" *ngIf="messages.length">
      <div class="message" [@down]="message.display" *ngFor="let message of messages" (mouseenter)="mouseenter(message)" (mouseleave)="mouseleave(message)">
        <span class="close" (click)="close(message)"><i>&#xe001;</i></span>
        <p [ngClass]="message.type">{{message.message}}</p>
      </div>
    </div>`,
  styleUrls: ['./headtips.component.scss'],
  animations: [
    trigger("down", [
      state("false", style({transform: "translate3d(0, -100%, 0)", opacity: 0})),
      state("true", style({transform: "translate3d(0, 0%, 0)", opacity: 1})),
      transition("false <=> true", animate(300))
    ])
  ],
  host: {class: "ss-platform-headtips-wraper"},
  encapsulation: ViewEncapsulation.None
})
export class HeadtipsComponent implements OnInit {

  messages: Array<Message> = new Array<Message>();

  constructor(private $app: AppService) {
    $app.subscribe([GlobalEvent.ShowHeadtipsInfo, GlobalEvent.ShowHeadtipsWarning, GlobalEvent.ShowHeadtipsError], (_message, eventName) => {
      let message = {type: TypeMapping.get(eventName), display: false, message: _message, timeout: 0}
      setTimeout(() => {
        message.display = true;
        message.timeout = setTimeout(() => {
          message.display = false;
          setTimeout(() => {
            this.remove(message);
          }, 300)
        }, 1800);
      })
      this.messages.push(message);
    });
  }

  remove(message: Message): void {
    let indexOf = this.messages.indexOf(message);
    if (indexOf > -1) {
      this.messages.splice(indexOf, 1);
    }
  }

  mouseenter(message: Message) {
    clearTimeout(message.timeout);
  }

  mouseleave(message: Message) {
    message.timeout = setTimeout(() => {
      message.display = false;
      setTimeout(() => {
        this.remove(message);
      }, 300)
    }, 1800);
  }

  close(message: Message): void {
    this.remove(message);
  }

  ngOnInit(): void {
    // this.$app.publish(GlobalEvent.ShowHeadtipsError, "错误提示！");
  }
}
